package connection;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JTextArea;

import org.apache.log4j.Logger;

/**
 * Trida pro pripojeni k serveru FICS
 * 
 * @author dove
 * 
 */
public class Connection {

	private static final long serialVersionUID = 1L;

	private Socket fics;

	private BufferedReader br;

	private Reader read;

	private BufferedWriter bw;

	private final static Logger logger = Logger.getLogger("Log");

	/**
	 * Konstruktor zajistuje pripojeni k FICS
	 * 
	 * @param username
	 *            prihlasovaci jmeno
	 * @param password
	 *            heslo
	 */
	public Connection() {
		try {

			fics = new Socket("freechess.org", 5000);
			bw = new BufferedWriter(new OutputStreamWriter(fics
					.getOutputStream()));
			br = new BufferedReader(
					new InputStreamReader(fics.getInputStream()));
			read = new Reader(br, bw);
		} catch (UnknownHostException e1) {
			logger.error("", e1);
		} catch (IOException e1) {
			logger.error("", e1);
		}
	}

	/**
	 * Pripojuje k serveru
	 * 
	 * @param username
	 *            jmeno uzivatele
	 * @param password
	 *            heslo uzivatele
	 */
	public void connect(String username, String password) {
		read.setUsername(username);
		read.setPassword(password);
		read.start();
		Reader.connect();
	}

	/**
	 * Posila prikaz na server
	 * 
	 * @param command
	 *            prikaz
	 */
	public void sendString(String command) {
		try {
			bw.write(command + "\n");
			bw.flush();
		} catch (IOException e) {
			logger.error("", e);
		}
	}

	/**
	 * Zavira pripojeni k serveru
	 */
	public void closeConnection() {
		try {
			fics.close();
		} catch (IOException e) {
			logger.error("", e);
		}
	}

	/**
	 * Zda je pripojen
	 * 
	 * @return hodnotu o pripojeni
	 */
	public boolean isConnected() {
		if (fics != null) {
			return true;
		}
		return false;
	}

	/**
	 * Pro zpristupneni pole do ktereho se zapisuji informace ze serveru
	 * 
	 * @return textarea pro zapis
	 */
	public JTextArea getTextArea() {
		return read.getCon();
	}
}
